//
//  ZQLPushManager.m
//  MLX
//
//  Created by SY on 2018/12/4.
//  Copyright © 2018年 SY. All rights reserved.
//

#import "MLXPushManager.h"
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif
#import "JPUSHService.h"
#ifdef DEBUG
#define isApsForProduction NO
#else
#define isApsForProduction YES
#endif


@interface MLXPushManager()<JPUSHRegisterDelegate>
@property(nonatomic,copy) void(^receiveRemoteNotificationBlcok)(NSDictionary *userInfo,MLXApplicationState applicationState);
@end

@implementation MLXPushManager
static MLXPushManager* manager = nil;


static NSString *pushAppId = @"";

+(MLXPushManager *)shareManager{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[MLXPushManager alloc] init];
    });
    return manager;
}
- (instancetype)init{
    self = [super init];
    if (self) {
        self.justInBack = NO;
        self.clickNotification = NO;
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillResignCenter:) name:UIApplicationWillResignActiveNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillEnterForegroundCenter:) name:UIApplicationWillResignActiveNotification object:nil];
    }
    return  self;
}
-(void)applicationWillResignCenter:(UIApplication *)application{
    [MLXPushManager shareManager].justInBack = YES;
}
#pragma mark -即将进入前台
- (void)applicationWillEnterForegroundCenter:(UIApplication *)application{
    [MLXPushManager configurePushWithOptions:nil PushKey:pushAppId applicationReceiveRemoteNotificationBlcok:self.receiveRemoteNotificationBlcok];
}
+ (BOOL)isOpenRemoteNotification {
    UIUserNotificationSettings *setting = [[UIApplication sharedApplication] currentUserNotificationSettings];
    return UIUserNotificationTypeNone != setting.types;
}
/// 配置推送
+ (void)configurePushWithOptions:(NSDictionary*)launchOptions PushKey:(NSString *)pushKey applicationReceiveRemoteNotificationBlcok:(void(^)(NSDictionary *userInfo,MLXApplicationState applicationState))applicationReceiveRemoteNotificationBlcok{
    
    pushAppId = pushKey;
    // 注册
    [self registerRemoteNotification];
    
    if (![self isOpenRemoteNotification]) return;
    
    if (applicationReceiveRemoteNotificationBlcok)
       [MLXPushManager shareManager].receiveRemoteNotificationBlcok = applicationReceiveRemoteNotificationBlcok;
    
    //// 初始化
    [JPUSHService setupWithOption:launchOptions
                           appKey:pushKey
                          channel:nil
                 apsForProduction:isApsForProduction//是否生产环境. 如果为开发状态,设置为 NO; 如果为生产状态,应改为 YES.
            advertisingIdentifier:nil];
    // 如果通过点击推送通知启动应用
    if (launchOptions != nil) {
        NSDictionary *dictionary = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
        if (dictionary != nil) {
            [self clickRemoteNotification:dictionary];
            [self clearBadge];
        }
    }
    [self handleRemoteNotification:launchOptions fetchCompletionHandler:nil];
}
/// 注册远程通知
+ (void)registerRemoteNotification{
    //可以添加自定义categories
    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
    entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:[MLXPushManager shareManager]];
}
///在前台和状态栏收到远程消息
+(void)handleRemoteNotification:(NSDictionary*)notification fetchCompletionHandler:(nonnull void (^)(UIBackgroundFetchResult))completionHandler{
    if (!notification) return;
    
    [MLXPushManager handleRemoteNotification:notification];
#pragma mark - 应用从后台点击消息进
    if ([UIApplication sharedApplication].applicationState == UIApplicationStateInactive && ([MLXPushManager shareManager].justInBack)){
        [MLXPushManager clickRemoteNotification:notification];
        ![MLXPushManager shareManager].receiveRemoteNotificationBlcok ?: [MLXPushManager shareManager].receiveRemoteNotificationBlcok(notification, MLXApplicationStateInactiveAction);
    }
#pragma mark - App启动的时候
    else if ([UIApplication sharedApplication].applicationState == UIApplicationStateInactive && (![MLXPushManager shareManager].justInBack)){
        ![MLXPushManager shareManager].receiveRemoteNotificationBlcok ?: [MLXPushManager shareManager].receiveRemoteNotificationBlcok(notification, MLXApplicationStateForegroundStartAction);
    }else{
#pragma mark - 正在通知栏或前台
        if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive) {
            [self clearBadge];
           ![MLXPushManager shareManager].receiveRemoteNotificationBlcok ?: [MLXPushManager shareManager].receiveRemoteNotificationBlcok(notification, MLXApplicationStateForegroundActive);
        }
    }
    !completionHandler ?: completionHandler(UIBackgroundFetchResultNewData);
}
///处理远程通知转化而来的本地通知
+ (void)handleLocalNotificationForRemotePush:(UILocalNotification*)notification{
    if ([UIApplication sharedApplication].applicationState == UIApplicationStateInactive&&[MLXPushManager shareManager].justInBack)
    { // 如果用户点击通知进入
        [MLXPushManager clickRemoteNotification:notification.userInfo];
    }
    [MLXPushManager shareManager].clickNotification = YES;
}
#pragma mark -本地处理消息
+ (void)clickRemoteNotification:(NSDictionary*)notification{
    [MLXPushManager shareManager].justInBack = NO;
    [self clearBadge];
    //处理消息
    
}
///清除角标
+ (void)clearBadge{
    [JPUSHService resetBadge];
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
}
/// 设置tag和标签
+ (void)setTagsAndAlias:(NSSet<NSString *> *)tags completion:(void(^)(NSInteger iResCode, NSSet *iTags, NSInteger seq))completion userName:(NSString *)userName{
    [JPUSHService setTags:tags completion:completion seq:1];
    [JPUSHService setAlias:userName completion:nil seq:0];
}
+ (void)unregisterRemoteNotifications{
    [[UIApplication sharedApplication] unregisterForRemoteNotifications];
    [[NSNotificationCenter defaultCenter] postNotificationName:kJPFNetworkDidCloseNotification object:nil];
}
/*   调用极光API   */
+ (void)registerDeviceToken:(NSData *)deviceToken{
    [JPUSHService registerDeviceToken:deviceToken];
}
+ (void)handleRemoteNotification:(NSDictionary*)notification{
    [JPUSHService handleRemoteNotification:notification];
}
#pragma mark -JPUSHRegisterDelegate
// iOS 12 以上
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center openSettingsForNotification:(UNNotification *)notification API_AVAILABLE(ios(10.0)){
    NSDictionary * userInfo = notification.request.content.userInfo;
    [MLXPushManager handleRemoteNotification:userInfo fetchCompletionHandler:nil];
}
#pragma mark iOS 10 以上  远程推送
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler  API_AVAILABLE(ios(10.0)){
    NSDictionary * userInfo = notification.request.content.userInfo;
    [MLXPushManager handleRemoteNotification:userInfo fetchCompletionHandler:nil];
    // 需要执行这个方法，选择是否提醒用户，有 Badge、Sound、Alert 三种类型可以选择设置
    completionHandler(UNNotificationPresentationOptionSound);
}
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler API_AVAILABLE(ios(10.0)){
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    [MLXPushManager handleRemoteNotification:userInfo fetchCompletionHandler:nil];
    completionHandler();  // 系统要求执行这个方法
}
@end
